
package com.eltonkent.ui;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

import com.eltonkent.R;
import com.eltonkent.db.FolderListTable;
import com.eltonkent.ui.adapters.DialogFolderDetailsListAdapter;
import com.eltonkent.ui.adapters.DialogFolderListAdapter;
import com.eltonkent.ui.adapters.FolderListAdapter;
import com.eltonkent.ui.containers.DialogFolderListContainer;
import com.eltonkent.ui.containers.FolderDetailsContainer;
import com.eltonkent.ui.containers.FolderListContainer;
import com.eltonkent.util.ImageUtil;
import com.eltonkent.util.StringUtil;

public final class FolderListActivity extends ParentActivity
{
	private ListView list;
	private final int DLG_NEW_FOLDER = 10;
	private final int DLG_CHANGE_PWD = 40;
	private final int DLG_REMOVE_PWD = 50;
	private final int DLG_FOLDER_DETAILS = 55;
	private final int DLG_GET_PWD = 65;
	private final int DLG_ABOUT = 85;

	private final int MNU_CHANGE_PWD = 0x1A;
	private final int MNU_DELETE_PWD = 0x1B;

	private View.OnClickListener dialogCancel = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			resetFolderPreference();
			dismissDialog(DLG_NEW_FOLDER);
		}
	};

	private boolean isPasswordProtected;

	private FolderListContainer currentListItem;

	private AdapterView.OnItemClickListener listClickListener = new AdapterView.OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
		{
			currentListItem = (FolderListContainer) list.getAdapter().getItem(position);
			Log.e("UI", "List item clicked at position " + position);
			if(currentListItem.isLocked())
			{
				showDialog(DLG_GET_PWD);
			} else
			{
				showFolderContents();
			}
		}
	};

	private Dialog newFolderDialog;

	private String folderIcon;

	private String folderName;

	private boolean doesExist(String folderName)
	{
		FolderListTable table = new FolderListTable(getApplicationContext());
		return table.doesFolderExist(folderName);
	}

	private Dialog getChangePasswordDialog()
	{
		final Dialog changePassDialog = getCustomDialog(R.layout.dialog_changepassword,
				R.string.menu_change_pwd);
		Button[] okCancel = getOKCancelButtons(changePassDialog);
		Button btnOk = okCancel[0];
		Button btnCancel = okCancel[1];
		final TextView errorText = (TextView) changePassDialog.findViewById(R.id.errorText);
		final EditText currentPassword = (EditText) changePassDialog.findViewById(R.id.currentpwd);
		final EditText newPassword = (EditText) changePassDialog.findViewById(R.id.newPass);
		final EditText newPasswordRep = (EditText) changePassDialog.findViewById(R.id.repeatPass);
		btnOk.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				FolderListTable table = new FolderListTable(getApplicationContext());
				String folderPassword = table.getFolderPassword(currentListItem.getFolderName());
				if(!currentPassword.getText().toString().equals(folderPassword))
				{
					errorText.setText(R.string.password_inavlid);
					errorText.setVisibility(View.VISIBLE);
					return;
				}
				String validation = StringUtil.validatePassword(getApplicationContext(), newPassword
						.getText(), newPasswordRep.getText());
				if(!validation.equals("OK"))
				{
					errorText.setText(validation);
					errorText.setVisibility(View.VISIBLE);
					return;
				} else
				{
					FolderListTable table2 = new FolderListTable(getApplicationContext());
					table2.setFolderPassword(currentListItem.getFolderName(), newPassword.getText()
							.toString());

					changePassDialog.dismiss();
					errorText.setVisibility(View.GONE);
				}

			}
		});
		btnCancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				currentPassword.setText("");
				newPassword.setText("");
				newPasswordRep.setText("");
				changePassDialog.dismiss();
				errorText.setVisibility(View.GONE);
			}
		});
		return changePassDialog;
	}

	private Dialog getDeleteFolderDialog()
	{
		Log.e("UI", "edit folder dialog called!");
		final Dialog deleteFolderDialog = getCustomDialog(R.layout.dialog_deletefolder,
				R.string.delete_folder);
		Button[] okCancel = getOKCancelButtons(deleteFolderDialog);
		Button btnOk = okCancel[0];
		Button btnCancel = okCancel[1];
		btnCancel.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				deleteFolderDialog.dismiss();
			}
		});
		btnOk.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				FolderListTable table = new FolderListTable(getApplicationContext());
				table.deleteFolder(currentListItem.getFolderName());
				refreshList();
				deleteFolderDialog.dismiss();
			}
		});
		return deleteFolderDialog;
	}

	private Dialog getEditFolderDialog()
	{
		Log.e("UI", "edit folder dialog called!");

		final Dialog editFolderDialog = getCustomDialog(R.layout.dialog_editfolder, R.string.edit_folder);
		final EditText name = (EditText) editFolderDialog.findViewById(R.id.folderName);
		final EditText desc = (EditText) editFolderDialog.findViewById(R.id.folderDesc);
		final TextView errorText = (TextView) editFolderDialog.findViewById(R.id.errorText);
		Button[] okCancel = getOKCancelButtons(editFolderDialog);
		Button btnOk = okCancel[0];
		Button btnCancel = okCancel[1];
		btnOk.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				Log.d("UI", "The folder name is empty" + name.getText().length());
				if(name.getText().length() == 0)
				{

					errorText.setText(R.string.create_folder_enter_folder_name);
					errorText.setVisibility(View.VISIBLE);
				} else
				{
					if(!name.getText().toString().equals(currentListItem.getFolderName())
							|| !desc.getText().toString().equals(currentListItem.getFolderDesc()))
					{
						FolderListTable table = new FolderListTable(getApplicationContext());
						table.updateFolder(currentListItem.getFolderName(), name.getText().toString(), desc
								.getText().toString());
						refreshList();
						editFolderDialog.dismiss();

					}

				}
			}
		});
		btnCancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				editFolderDialog.dismiss();
				errorText.setVisibility(View.GONE);
			}
		});
		return editFolderDialog;
	}

	private Dialog getFolderDetailsDialog()
	{
		final Dialog changePassDialog = getCustomDialog(R.layout.dialog_listdisplay, currentListItem
				.getFolderName());
		setFolderListDetails(changePassDialog);
		return changePassDialog;
	}

	private Dialog getFolderListDialog()
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_listdisplay, R.string.create_folder_type);
		final ListView list = (ListView) dialog.findViewById(R.id.detailList);
		list.setDividerHeight(0);
		String[] folderNames = getResources().getStringArray(R.array.folder_category);
		String[] folderIcons = getResources().getStringArray(R.array.folder_icon);
		DialogFolderListContainer[] listContainer = new DialogFolderListContainer[folderNames.length];
		for(int i = 0; i < folderNames.length; i++)
		{
			listContainer[i] = new DialogFolderListContainer(folderNames[i], folderIcons[i]);

		}
		DialogFolderListAdapter adapter = new DialogFolderListAdapter(getApplicationContext(),
				R.layout.listview_icon_singleline, listContainer);
		list.setAdapter(adapter);

		list.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				DialogFolderListContainer cont = (DialogFolderListContainer) list.getAdapter()
						.getItem(arg2);
				folderName = cont.getFolderName();
				folderIcon = cont.getFolderIcon();
				refreshFolderType();
				dialog.dismiss();
			}
		});
		return dialog;
	}

	private Dialog getNewFolderDialog()
	{
		newFolderDialog = new Dialog(this);
		newFolderDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		newFolderDialog.setContentView(R.layout.dialog_createfolder);

		final EditText folderName = (EditText) newFolderDialog.findViewById(R.id.folderName);
		final EditText folderDesc = (EditText) newFolderDialog.findViewById(R.id.folderDesc);

		/* Set the button listeners */
		Button[] okCancel = getOKCancelButtons(newFolderDialog);
		Button btnok = okCancel[0];
		Button btnCancel = okCancel[1];
		btnCancel.setOnClickListener(dialogCancel);
		Button quit = (Button) newFolderDialog.findViewById(R.id.quitButton);
		quit.setOnClickListener(dialogCancel);
		final CheckBox passwordProtect = (CheckBox) newFolderDialog.findViewById(R.id.togglePassword);
		final View passwordLayout = newFolderDialog.findViewById(R.id.passwordPanel);
		passwordLayout.setVisibility(View.GONE);
		final EditText password = (EditText) newFolderDialog.findViewById(R.id.newPass);
		final EditText passwordRepeat = (EditText) newFolderDialog.findViewById(R.id.repeatPass);
		final TextView errorText = (TextView) newFolderDialog.findViewById(R.id.errorText);
		View folderType = newFolderDialog.findViewById(R.id.folderLayout);
		folderType.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				/* show folder list */
				showDialog(ApplicationConstants.DIALOG_SELECT);
			}
		});
		passwordProtect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				isPasswordProtected = isChecked;
				if(isChecked)
				{
					passwordLayout.setVisibility(View.VISIBLE);
				} else
				{
					passwordLayout.setVisibility(View.GONE);
				}
			}
		});

		btnok.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				if(folderName.getText().toString().equals(""))
				{
					errorText.setText(R.string.create_folder_enter_folder_name);
					errorText.setVisibility(View.VISIBLE);
					return;
				} else
				{
					errorText.setVisibility(View.GONE);
					if(doesExist(folderName.getText().toString()))
					{
						errorText.setText(R.string.create_folder_exists);
						errorText.setVisibility(View.VISIBLE);
						return;
					} else if(isPasswordProtected)
					{
						String validate = StringUtil.validatePassword(getApplicationContext(), password
								.getText(), passwordRepeat.getText());
						if(!validate.equals("OK"))
						{
							errorText.setText(validate);
							errorText.setVisibility(View.VISIBLE);
							return;
						}
					}
					// Add to DB
					FolderListTable table = new FolderListTable(getApplicationContext());
					table.addFolder(folderName.getText().toString(), folderDesc.getText().toString(),
							folderIcon, isPasswordProtected ? password.getText().toString() : null);
					refreshList();
					newFolderDialog.dismiss();
					passwordLayout.setVisibility(View.GONE);
					errorText.setVisibility(View.GONE);
					passwordProtect.setChecked(false);
					password.setText("");
					passwordRepeat.setText("");
					folderDesc.setText("");
					folderName.setText("");
					resetFolderPreference();

				}
				Log.d("UI", "Folder name text " + folderName.getText());
			}
		});
		return newFolderDialog;
	}

	private Dialog getPasswordDialog(final boolean removePassword)
	{
		final Dialog passwordDialog = getCustomDialog(R.layout.dialog_removepassword,
				R.string.enter_folder_password);
		final EditText password = (EditText) passwordDialog.findViewById(R.id.password);

		final TextView errorText = (TextView) passwordDialog.findViewById(R.id.error_Text);
		Button[] okCancel = getOKCancelButtons(passwordDialog);
		Button btnok = okCancel[0];
		Button btnCancel = okCancel[1];
		btnCancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				passwordDialog.dismiss();
				errorText.setVisibility(View.GONE);
				password.setText("");
			}
		});

		btnok.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				FolderListTable table = new FolderListTable(getApplicationContext());
				final String pass = table.getFolderPassword(currentListItem.getFolderName());
				Log.e("UI", "Folder password->" + pass);
				if(!pass.equals(password.getText().toString()))
				{
					errorText.setVisibility(View.VISIBLE);
					return;
				} else if(removePassword)
				{
					FolderListTable table2 = new FolderListTable(getApplicationContext());
					table2.removeFolderPassword(currentListItem.getFolderName());
					refreshList();

				} else
				{
					showFolderContents();
				}

				passwordDialog.dismiss();
				errorText.setVisibility(View.GONE);
				password.setText("");
			}
		});

		return passwordDialog;
	}

	@Override
	public boolean onContextItemSelected(MenuItem menuItem)
	{
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) menuItem.getMenuInfo();
		currentListItem = (FolderListContainer) list.getAdapter().getItem(menuInfo.position);
		switch(menuItem.getItemId())
		{
			// case R.id.mnu_folderList_Details:
			// showDialog(DLG_FOLDER_DETAILS);
			// return true;
			case R.id.mnu_folderList_Edit:
				showDialog(ApplicationConstants.DIALOG_EDIT);
				return true;
			case R.id.mnu_folderList_Delete:
				showDialog(ApplicationConstants.DIALOG_DELETE);
				return true;
			case MNU_CHANGE_PWD:
				showDialog(DLG_CHANGE_PWD);
				return true;
			case MNU_DELETE_PWD:
				showDialog(DLG_REMOVE_PWD);
				return true;
		}
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		currentListItem = (FolderListContainer) list.getAdapter().getItem(info.position);
		Log.d("UI", "Current selected item " + currentListItem.getFolderName());
		inflateMenu(menu, R.menu.folderlistcontextmenu);
		if(currentListItem.isLocked())
		{
			menu.add(0, MNU_CHANGE_PWD, 0, R.string.menu_change_pwd);
			menu.add(0, MNU_DELETE_PWD, 0, R.string.menu_remove_pwd);
		}
	}

	@Override
	protected final Dialog onCreateDialog(int id)
	{
		switch(id)
		{
			case DLG_NEW_FOLDER:
				return getNewFolderDialog();
			case ApplicationConstants.DIALOG_DELETE:
				return getDeleteFolderDialog();
			case ApplicationConstants.DIALOG_EDIT:
				return getEditFolderDialog();
			case DLG_CHANGE_PWD:
				return getChangePasswordDialog();
			case DLG_REMOVE_PWD:
				return getPasswordDialog(true);
			case DLG_GET_PWD:
				return getPasswordDialog(false);
			case DLG_FOLDER_DETAILS:
				return getFolderDetailsDialog();
			case ApplicationConstants.DIALOG_SELECT:
				return getFolderListDialog();
			case DLG_ABOUT:
				return getAboutDialog();
			default:
				return super.onCreateDialog(id);
		}
	}

	private Dialog getAboutDialog()
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_about, R.string.menu_about);
		PackageManager manager = getPackageManager();
		PackageInfo info = null;
		try
		{
			info = manager.getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
		} catch(NameNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String version = "AndItsSafe v" + String.valueOf(info.versionCode);
		TextView texttitle = (TextView) dialog.findViewById(R.id.aboutTitle);
		texttitle.setText(version);
		return dialog;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		inflateMenu(menu, R.menu.folderlistmenu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
			/* Add new folder */
			case R.id.mnu_AddFolder:
				showDialog(DLG_NEW_FOLDER);
				return true;
			case R.id.mnu_Settings:
				Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
				startActivity(intent);
				return true;
			case R.id.mnu_About:
				showDialog(DLG_ABOUT);
			default:
				return false;
		}

	}

	protected void onResume()
	{
		super.onResume();
		Log.d("UI", "onResume on Folder list activity");
		refreshList();
	}

	@Override
	protected void onPrepareDialog(int id, final Dialog dialog)
	{
		Log.d("UI", "Current List item->" + currentListItem);
		switch(id)
		{
			case ApplicationConstants.DIALOG_DELETE:
				TextView caption = (TextView) dialog.findViewById(R.id.dialogText);
				String captionText = getResources().getString(R.string.delete_folder) + " "
						+ currentListItem.getFolderName() + "?";
				caption.setText(captionText);
				return;
			case ApplicationConstants.DIALOG_EDIT:
				EditText name = (EditText) dialog.findViewById(R.id.folderName);
				name.setText(currentListItem.getFolderName());
				EditText desc = (EditText) dialog.findViewById(R.id.folderDesc);
				desc.setText(currentListItem.getFolderDesc());
				return;

			case DLG_REMOVE_PWD:
				final EditText password = (EditText) dialog.findViewById(R.id.password);
				final TextView errorText2 = (TextView) dialog.findViewById(R.id.error_Text);
				password.setText("");
				errorText2.setVisibility(View.GONE);
				return;
			case DLG_NEW_FOLDER:

				refreshFolderType();
				return;
		}
	}

	@Override
	public Object[] onRetainNonConfigurationInstance()
	{
		return new Object[]
		{ currentListItem, folderIcon, folderName };
	}

	@Override
	protected void populateUI()
	{
		// refreshList();
		setToPath(getResources().getString(R.string.folder_activity_title));
		Object[] retainedData = (Object[]) this.getLastNonConfigurationInstance();
		if(retainedData != null)
		{
			currentListItem = (FolderListContainer) retainedData[0];
			folderIcon = (String) retainedData[1];
			folderName = (String) retainedData[2];
		}
		showExitButton();
	}

	private void refreshFolderType()
	{
		if(folderIcon == null || folderName == null)
		{
			resetFolderPreference();
		}
		ImageView image = (ImageView) newFolderDialog.findViewById(R.id.folderIcon);

		TextView text = (TextView) newFolderDialog.findViewById(R.id.folderType);
		image.setImageBitmap(ImageUtil.createBitmapFromAsset(getApplicationContext(), folderIcon));
		text.setText(folderName);
	}

	private void refreshList()
	{
		FolderListTable table = new FolderListTable(getApplicationContext());
		FolderListAdapter adapter = new FolderListAdapter(getApplicationPreferences(),
				getApplicationContext(), R.layout.listview_icon_double_line, table.getFolders());
		list.setAdapter(adapter);
		setStatusText(adapter.getCount() + " " + getResources().getString(R.string.total_items));
	}

	private void resetFolderPreference()
	{
		folderIcon = "folder/folder.png";
		folderName = getResources().getString(R.string.general);
	}

	private void setFolderListDetails(Dialog dialog)
	{
		ListView detailList = (ListView) dialog.findViewById(R.id.detailList);
		FolderDetailsContainer[] listData = new FolderListTable(getApplicationContext()).getFolderDetails(
				getResources().getStringArray(R.array.folder_details), currentListItem.getFolderName());
		detailList.setAdapter(new DialogFolderDetailsListAdapter(getApplicationContext(),
				R.layout.listview_double_line, listData));
	}

	@Override
	protected void setupUI(Bundle savedInstance)
	{
		setContentView(R.layout.activity_genericlist);
		list = (ListView) findViewById(R.id.folderList);
		list.setDividerHeight(0);
		registerForContextMenu(list);
		list.setOnItemClickListener(listClickListener);
	}

	private void showFolderContents()
	{
		Intent folderContents = new Intent(this, SafeEntriesActivity.class);
		folderContents.putExtra(ApplicationConstants.EXTRA_FOLDER_NAME, currentListItem.getFolderName());
		// folderContents.putExtra(ActivityConstants.EXTRA_FOLDER_ICON,
		// currentListItem.getFolderType());
		startActivity(folderContents);
	}
}
